package com.application.admin;

import com.application.validate.StatsParamValidator;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台统计
 */
@Controller("/admin/stats")
public class StatsController extends BaseController {

    private final String sql_select = "com.application.stats.productSelect";
    private final String sql_from = "com.application.stats.productFrom";
    private final String sql_skuSelect = "com.application.stats.productSkuSelect";
    private final String sql_skuFrom = "com.application.stats.productSkuFrom";

    /**
     * 参数：开始时间startDate，结束时间endDate，区域ID：areaId
     */
    @Before(StatsParamValidator.class)
    public void product() {
        splitPage.getQueryParam().put("areaId", getAttr("areaId"));
        splitPage.getQueryParam().put("userid", getAttr("userid"));
        paging(splitPage, sql_select, sql_from);
        List<Record> list = (List<Record>) splitPage.getList();

        splitPage.setExtData(getProductTotal());

        renderOk(splitPage);
    }

    private Map<String, String> getProductTotal() {
        String fromSql = getSqlByBeetl(sql_from, splitPage.getQueryParam());
        StringBuffer sb = new StringBuffer(1000);
        sb.append("select sum(totalPrice) as price, sum(totalWeight) as weight, sum(totalAmount) as amount, sum(totalVipPrice) as price2 ");
        sb.append("from (select totalPrice,totalWeight,totalAmount,totalVipPrice " + fromSql + ") t");

        Record data = Db.findFirst(sb.toString());
        Map<String, String> map = new HashMap<>();
        map.put("totalWeight", data.get("weight"));
        map.put("totalPrice", data.get("price"));
        map.put("totalVipPrice", data.get("price2"));
        map.put("totalAmount", data.get("amount"));
        return map;
    }

    /**
     * 参数同product接口,
     *
     * @param产品(pid)
     */
    @Before(StatsParamValidator.class)
    public void productSku() {
        //根据地区名称查询对应的编码信息
        splitPage.getQueryParam().put("areaId", getAttr("areaId"));
        splitPage.getQueryParam().put("userid", getAttr("userid"));
        paging(splitPage, sql_skuSelect, sql_skuFrom);
        renderOk(splitPage);
    }
}
